#ifndef __THREAD_POOL__
#define __THREAD_POOL__
#include "threadsafe_queue.h"
#include "join_threads.h"
#include "function_wrapper.h"
#include <atomic>
#include <thread>
#include <vector>
#include <functional>
#include <future>
#include <type_traits>

using std::thread;
using std::vector;
using std::atomic_bool;
using std::function;
using std::future;
using std::packaged_task;

// v2 : 等待任务完成 令submit()返回任务句柄
class thread_pool
{
    // using task_type = function<void()>; //v2自定义函数类型function_wrapper替代
private:
    atomic_bool _done;
    threadsafe_queue<function_wrapper> _work_queue; // 工作队列
    size_t _thread_num;
    vector<thread>  _threads;
    join_threads _joiner; // 自动汇合全部线程:成员中第一个被销毁

    void worker_thread(); // 线程取任务执行
public:
    thread_pool(size_t thread_num);
    ~thread_pool();
    template <typename FunctionType>
    future<typename std::result_of<FunctionType()>::type> //编译时推断可调用对象的返回类型
    submit(FunctionType f)
    {
        using result_type = typename std::result_of<FunctionType()>::type;
        packaged_task<result_type()> task(std::move(f));
        future<result_type> res(task.get_future());
        _work_queue.push(std::move(task));
        return res;
    }

    /*void submit(FunctionType f)
    {
        //将函数or可调用对象包装为std::function实例 再压入队列
        _work_queue.push(function<void()>(f));
    }*/
};
#endif